﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using BP.DA;
using BP.Sys;
using BP.Web;
using BP.Port;
using BP.En;
using BP.WF;
using BP.WF.Template;
using BP.Difference;
using System.IO;
using System.Linq;
using BP.CCBill;
using FluentFTP;
using Newtonsoft.Json.Linq;
using BP.CCBill.Template;
using static Microsoft.Extensions.Logging.EventSource.LoggingEventSource;

namespace BP.WF.HttpHandler
{
    /// <summary>
    /// 页面功能实体
    /// </summary>
    public class WF_CommTS : BP.WF.HttpHandler.DirectoryPageBase
    {
        #region 参数

        public string Paras
        {
            get { return this.GetRequestVal("Paras"); }
        }

        public string OrderBy
        {
            get { return this.GetRequestVal("OrderBy"); }
        }

        public string MyPK
        {
            get { return this.GetRequestVal("MyPK"); }
        }

        public string No
        {
            get { return this.GetRequestVal("No"); }
        }

        public int OID
        {
            get
            {
                string str = this.GetRequestVal("OID");
                if (DataType.IsNullOrEmpty(str))
                    str = this.GetRequestVal("WorkID");

                if (DataType.IsNullOrEmpty(str))
                    str = this.GetRequestVal("PKVal");

                if (DataType.IsNullOrEmpty(str) == true)
                    str = "0";
                return int.Parse(str);
            }
        }

        public string ClassID
        {
            get { return this.GetRequestVal("ClassID"); }
        }

        /// <summary>
        /// 关联服务器端的实体类.
        /// </summary>
        public string RefEnName
        {
            get
            {
                string str = this.GetRequestVal("RefEnName");
                if (DataType.IsNullOrEmpty(str) == false)
                    str = str.Replace("TS.", "BP.");
                return str;
            }
        }

        public string KVs
        {
            get { return this.GetRequestVal("KVs"); }
        }

        public string Map
        {
            get { return this.GetRequestVal("Map"); }
        }

        public string PK
        {
            get { return this.GetRequestVal("PK"); }
        }

        public string PKVal
        {
            get { return this.GetRequestVal("PKVal"); }
        }

        public int PKValInt
        {
            get
            {
                string str = this.GetRequestVal("PKVal");


                if (DataType.IsNullOrEmpty(str) == true)
                    str = this.GetRequestVal("WorkID");
                else
                    return int.Parse(str);

                if (DataType.IsNullOrEmpty(str) == true)
                    str = this.GetRequestVal("NodeID");
                else
                    return int.Parse(str);

                if (DataType.IsNullOrEmpty(str) == true)
                    str = this.GetRequestVal("OID");
                else
                    return int.Parse(str);

                if (DataType.IsNullOrEmpty(str) == true)
                    str = "0";

                return int.Parse(str);
            }
        }

        #endregion 参数

        /// <summary>
        /// 构造函数
        /// </summary>
        public WF_CommTS()
        {
        }

        /// <summary>
        /// 实体移动.
        /// </summary>
        /// <returns></returns>
        public string TreeEns_ItemsMove()
        {
            Entity en = ClassFactory.GetEn(this.EnName);
            string pTable = en.EnMap.PhysicsTable;
            string pk = en.PK;

            string sourceNos = this.GetRequestVal("SourceNos");

            string[] flowNos = sourceNos.Split(',');
            for (int i = 0; i < flowNos.Length; i++)
            {
                string flowNo = flowNos[i];
                string sql = "UPDATE " + pTable + " SET  Idx=" + i + " WHERE " + pk + "='" + flowNo + "'";
                DBAccess.RunSQL(sql);
            }

            return "流程顺序移动成功..";
        }

        /// <summary>
        /// 移动到一个节点下
        /// </summary>
        /// <returns></returns>
        public string TreeEns_MoveToSort()
        {
            //初始化实体.
            GEEntity en = new GEEntity(this.EnName, this.PKVal);
            string nodeID = this.GetRequestVal("NodeID");

            string refKey = this.GetRequestVal("RefKey");
            en.SetValByKey(refKey, nodeID);
            en.Update();
            return "流程顺序移动成功..";
        }

        /// <summary>
        /// 获得数据
        /// </summary>
        /// <returns></returns>
        public string DataPacket_GenerDB()
        {
            DataPacketBase en = ClassFactory.GetDataPacket(this.EnName);
            en.Init();
            DataSet ds = en.GenerData();
            return BP.Tools.Json.ToJson(ds);
        }

        #region 页面类.

        /// <summary>
        /// 从表移动
        /// </summary>
        /// <returns></returns>
        public string DtlSearch_UpdatIdx()
        {
            Map map = BP.EnTS.Glo.GenerMap(this.ClassID);

            string pk = "No";
            if (map.Attrs.Contains("No") == true)
                pk = "No";
            else if (map.Attrs.Contains("OID") == true)
                pk = "OID";
            else if (map.Attrs.Contains("MyPK") == true)
                pk = "MyPK";
            else if (map.Attrs.Contains("NodeID") == true)
                pk = "NodeID";
            else if (map.Attrs.Contains("WorkID") == true)
                pk = "WorkID";

            string[] pks = this.GetRequestVal("PKs").Split(',');
            int idx = 0;
            foreach (string str in pks)
            {
                if (DataType.IsNullOrEmpty(str) == true)
                    continue;
                idx++;
                string sql = "UPDATE " + map.PhysicsTable + " SET Idx=" + idx + " WHERE " + pk + "='" + str + "'";
                DBAccess.RunSQL(sql);
            }

            #region 特殊业务处理.

            if (this.ClassID.Equals("TS.WF.Cond") == true)
            {
                //判断设置的顺序是否合理？
                Cond cond = new Cond();
                string pkval = pks[0];
                cond.MyPK = pkval;
                cond.Retrieve();

                return WF_Admin_Cond2020.List_DoCheckExt(cond.CondTypeInt, cond.NodeID, cond.ToNodeID);
            }

            #endregion 特殊业务处理.


            return "移动成功.";
        }


        /// <summary>
        /// 更新排序
        /// </summary>
        /// <returns></returns>
        public string TreeEns_UpdateDtlIdx()
        {
            string idList = GetRequestVal("PKs");
            if (string.IsNullOrWhiteSpace(idList))
            {
                return "err@请传入排序集合";
            }

            string tableName = GetRequestVal("PTable");
            if (string.IsNullOrWhiteSpace(tableName))
            {
                return "err@请传入物理表名";
            }

            string tablePK = GetRequestVal("PK");
            if (string.IsNullOrWhiteSpace(tablePK))
            {
                return "err@请传入物理表主键";
            }

            var targetIdList = idList.Split(',', StringSplitOptions.RemoveEmptyEntries)
                .Select(id => $"'{id.Trim()}'")
                .ToArray();
            if (!targetIdList.Any())
            {
                return "err@排序集合不能为空";
            }

            string minIdxSQL =
                $"SELECT MIN(Idx) FROM {tableName} WHERE {tablePK} IN ({string.Join(",", targetIdList)})";
            int minIdx = DBAccess.RunSQLReturnValInt(minIdxSQL);

            // 更新其他部分 SQL
            string updateOthersSQL = $"UPDATE {tableName} SET Idx = Idx + {targetIdList.Length} WHERE Idx = 0";
            DBAccess.RunSQL(updateOthersSQL);

            // 构建批量更新的 SQL
            var batchUpdateIdxSQL = new StringBuilder();
            foreach (var id in targetIdList)
            {
                batchUpdateIdxSQL.Append($"UPDATE {tableName} SET Idx = {minIdx} WHERE {tablePK} = {id};");
                minIdx++;
            }

            DBAccess.RunSQLs(batchUpdateIdxSQL.ToString());
            return "排序成功";
            // string[] pks = this.GetRequestVal("PKs").Split(',');
            // string ptable = this.GetRequestVal("PTable");
            // string pk = this.GetRequestVal("PK");
            // int idx = 0;
            // foreach (string str in pks)
            // {
            //     if (DataType.IsNullOrEmpty(str) == true)
            //         continue;
            //     idx++;
            //     string sql = "UPDATE " + ptable + " SET Idx='" + idx + "' WHERE " + pk + "='" + str + "'";
            //     DBAccess.RunSQL(sql);
            // }
            // return "执行成功.";
        }

        #endregion 页面类.

        #region 权限控制.

        /// <summary>
        /// 系统类实体.
        /// </summary>
        public static string SysTSEntity = "TS.WF,TS.FlowData,TS.TSClass,TS.GPM,TS.MapExt,TS.Port,TS.Sys,TS.AttrNode," +
                                           "TS.CCBill,TS.Frm,TS.FrmUI,TS.AttrFlow,TS.CCFast,TS.SaaS,";

        /// <summary>
        /// 对系统实体的增加,删除,修改只有管理员或者二级管理员才能执行.
        /// </summary>
        /// <param name="pkval"></param>
        /// <param name="checkType"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool CheckAdminPower(string pkval, string checkType)
        {
            #region 判断admin处理权限.

            if (WebUser.IsAdmin == false)
            {
                string[] strs = this.ClassID.Split('.');
                string clsID = strs[0] + "." + strs[1]; //拼接前两部分.
                if (SysTSEntity.IndexOf(clsID + ",") >= 0)
                {
                    /*说明是系统实体*/
                    throw new Exception("err@非管理员没有:" + checkType + " [" + this.ClassID + "]的权限.");
                }
            }

            #endregion 处理权限.

            return true;
        }

        /// <summary>
        /// 检查删除权限
        /// </summary>
        /// <param name="tableName">实体ID</param>
        /// <param name="en">实体</param>
        /// <returns>返回是否可以删除?</returns>
        public bool CheckDeletePower(string tableName, Entity en)
        {
            DBSafes ens = BP.DA.Cache2024.GetDBSafes(tableName);
            if (ens.Count == 0) return true;

            //遍历数据.
            foreach (DBSafe item in ens)
            {
                string dbRole = item.GetValStrByKey("DBRole");
                if (dbRole.Equals("RecDelete") == false)
                    continue;

                string markID = item.GetValStrByKey("MarkID");
                if (markID.Equals("None") == true)
                    return true;

                string docs = item.GetValStrByKey("Docs"); //控制内容. 

                //只能删除自己创建的.
                if (markID.Equals("SelfOnly") == true)
                {
                    Attrs attrs = en.EnMap.Attrs;
                    if (attrs.Contains("RecNo") == true && en.GetValStrByKey("RecNo").Equals(WebUser.No) == true)
                        return true;
                    if (attrs.Contains("FK_Emp") == true && en.GetValStrByKey("FK_Emp").Equals(WebUser.No) == true)
                        return true;
                    if (attrs.Contains("StarterNo") == true &&
                        en.GetValStrByKey("StarterNo").Equals(WebUser.No) == true)
                        return true;
                    if (attrs.Contains("EmpNo") == true && en.GetValStrByKey("EmpNo").Equals(WebUser.No) == true)
                        return true;
                }

                //集团应用.
                if (markID.Equals("ByOrg") == true)
                {
                    Attrs attrs = en.EnMap.Attrs;
                    if (attrs.Contains("OrgNo") == true && en.GetValStrByKey("OrgNo").Equals(WebUser.OrgNo) == true)
                        return true;
                }

                if (markID.Equals("DeptLeader") == true)
                {
                    string sql =
                        "SELECT Leader FROM Port_Dept WHERE No IN (SELECT FK_Dept FROM Port_DeptEmp WHERE FK_Emp='" +
                        WebUser.No + "')";
                    string empNo = DBAccess.RunSQLReturnStringIsNull(sql, "");
                    if (empNo.Equals(WebUser.No) == true)
                        return true;
                }

                if (markID.Equals("ByStations") == true)
                {
                    string sql = "SELECT FK_Station FROM Port_DeptEmpStation WHERE FK_Emp='" + WebUser.No + "'";
                    DataTable dt = DBAccess.RunSQLReturnTable(sql);
                    string vals = "," + docs + ",";
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (vals.Contains("," + dr[0].ToString() + ",") == true)
                            return true;
                    }
                }

                if (markID.Equals("ByDepts") == true)
                {
                    string sql = "SELECT FK_Dept FROM Port_DeptEmp WHERE FK_Emp='" + WebUser.No + "'";
                    DataTable dt = DBAccess.RunSQLReturnTable(sql);
                    string vals = "," + docs + ",";
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (vals.Contains("," + dr[0].ToString() + ",") == true)
                            return true;
                    }
                }

                if (markID.Equals("ByEmps") == true)
                {
                    string vals = "," + docs + ",";
                    if (vals.Contains("," + WebUser.No + ",") == true)
                        return true;
                }

                if (markID.Equals("Adminer") == true && WebUser.No.Equals("admin"))
                    return true;
                if (markID.Equals("Admin2") == true && WebUser.IsAdmin == true)
                    return true;
            }

            throw new Exception("err@对数据[" + this.ClassID + "],PKVal=" + en.PKVal + ",没有删除的权限.");
        }

        /// <summary>
        /// 检查更新权限
        /// </summary>
        /// <param name="tableName">实体ID</param>
        /// <param name="en">实体</param>
        /// <returns>返回是否可以删除?</returns>
        public bool CheckUpdatePower(string tableName, Entity en)
        {
            DBSafes ens = BP.DA.Cache2024.GetDBSafes(tableName);
            if (ens.Count == 0) return true;
            //遍历数据.
            foreach (DBSafe item in ens)
            {
                string dbRole = item.GetValStrByKey("DBRole");
                if (dbRole.Equals("RecSave") == false)
                    continue;

                string markID = item.GetValStrByKey("MarkID");
                if (markID.Equals("None") == true)
                    return true;

                string docs = item.GetValStrByKey("Docs"); //控制内容. 

                //只能删除自己创建的.
                if (markID.Equals("SelfOnly") == true)
                {
                    Attrs attrs = en.EnMap.Attrs;
                    if (attrs.Contains("RecNo") == true && en.GetValStrByKey("RecNo").Equals(WebUser.No) == true)
                        return true;
                    if (attrs.Contains("FK_Emp") == true && en.GetValStrByKey("FK_Emp").Equals(WebUser.No) == true)
                        return true;
                    if (attrs.Contains("StarterNo") == true &&
                        en.GetValStrByKey("StarterNo").Equals(WebUser.No) == true)
                        return true;
                    if (attrs.Contains("EmpNo") == true && en.GetValStrByKey("EmpNo").Equals(WebUser.No) == true)
                        return true;
                }

                //集团应用.
                if (markID.Equals("ByOrg") == true)
                {
                    Attrs attrs = en.EnMap.Attrs;
                    if (attrs.Contains("OrgNo") == true && en.GetValStrByKey("OrgNo").Equals(WebUser.OrgNo) == true)
                        return true;
                }

                if (markID.Equals("DeptLeader") == true)
                {
                    string sql =
                        "SELECT Leader FROM Port_Dept WHERE No IN (SELECT FK_Dept FROM Port_DeptEmp WHERE FK_Emp='" +
                        WebUser.No + "')";
                    string empNo = DBAccess.RunSQLReturnStringIsNull(sql, "");
                    if (empNo.Equals(WebUser.No) == true)
                        return true;
                }

                if (markID.Equals("ByStations") == true)
                {
                    string sql = "SELECT FK_Station FROM Port_DeptEmpStation WHERE FK_Emp='" + WebUser.No + "'";
                    DataTable dt = DBAccess.RunSQLReturnTable(sql);
                    string vals = "," + docs + ",";
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (vals.Contains("," + dr[0].ToString() + ",") == true)
                            return true;
                    }
                }

                if (markID.Equals("ByDepts") == true)
                {
                    string sql = "SELECT FK_Dept FROM Port_DeptEmp WHERE FK_Emp='" + WebUser.No + "'";
                    DataTable dt = DBAccess.RunSQLReturnTable(sql);
                    string vals = "," + docs + ",";
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (vals.Contains("," + dr[0].ToString() + ",") == true)
                            return true;
                    }
                }

                if (markID.Equals("ByEmps") == true)
                {
                    string vals = "," + docs + ",";
                    if (vals.Contains("," + WebUser.No + ",") == true)
                        return true;
                }

                if (markID.Equals("Adminer") == true && WebUser.No.Equals("admin"))
                    return true;
                if (markID.Equals("Admin2") == true && WebUser.IsAdmin == true)
                    return true;
            }

            throw new Exception("err@对数据[" + this.ClassID + "],PKVal=" + en.PKVal + ",没有删除的权限.");
        }

        public bool CheckInsertPower(string tableName)
        {
            DBSafes ens = BP.DA.Cache2024.GetDBSafes(tableName);

            if (ens.Count == 0) return true;

            //遍历数据.
            foreach (DBSafe item in ens)
            {
                string dbRole = item.GetValStrByKey("DBRole");
                if (dbRole.Equals("RecNew") == false)
                    continue;

                string markID = item.GetValStrByKey("MarkID");
                if (markID.Equals("None") == true)
                    return true;
                string docs = item.GetValStrByKey("Docs"); //控制内容. 

                if (markID.Equals("DeptLeader") == true)
                {
                    string sql =
                        "SELECT Leader FROM Port_Dept WHERE No IN (SELECT FK_Dept FROM Port_DeptEmp WHERE FK_Emp='" +
                        WebUser.No + "')";
                    string empNo = DBAccess.RunSQLReturnStringIsNull(sql, "");
                    if (empNo.Equals(WebUser.No) == true)
                        return true;
                }

                if (markID.Equals("ByStations") == true)
                {
                    string sql = "SELECT FK_Station FROM Port_DeptEmpStation WHERE FK_Emp='" + WebUser.No + "'";
                    DataTable dt = DBAccess.RunSQLReturnTable(sql);
                    string vals = "," + docs + ",";
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (vals.Contains("," + dr[0].ToString() + ",") == true)
                            return true;
                    }
                }

                if (markID.Equals("ByDepts") == true)
                {
                    string sql = "SELECT FK_Dept FROM Port_DeptEmp WHERE FK_Emp='" + WebUser.No + "'";
                    DataTable dt = DBAccess.RunSQLReturnTable(sql);
                    string vals = "," + docs + ",";
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (vals.Contains("," + dr[0].ToString() + ",") == true)
                            return true;
                    }
                }

                if (markID.Equals("ByEmps") == true)
                {
                    string vals = "," + docs + ",";
                    if (vals.Contains("," + WebUser.No + ",") == true)
                        return true;
                }

                if (markID.Equals("Adminer") == true && WebUser.No.Equals("admin"))
                    return true;
                if (markID.Equals("Admin2") == true && WebUser.IsAdmin == true)
                    return true;
            }

            throw new Exception("err@对数据[" + this.ClassID + "]没有Insert的权限.");
        }

        #endregion 权限控制.

        #region 实体集合操作.

        public string Entities_RetrieveAllFromDBSource()
        {
            if (this.PK.Equals("No") == true)
            {
                TSEntitiesNoName ens = new TSEntitiesNoName(this.ClassID);
                ens.RetrieveAllFromDBSource();
                return ens.ToJson();
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntitiesOID ens = new TSEntitiesOID(this.ClassID);
                ens.RetrieveAllFromDBSource();
                return ens.ToJson();
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntitiesMyPK ens = new TSEntitiesMyPK(this.ClassID);
                ens.RetrieveAllFromDBSource();
                return ens.ToJson();
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntitiesWorkID ens = new TSEntitiesWorkID(this.ClassID);
                ens.RetrieveAllFromDBSource();
                return ens.ToJson();
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntitiesNodeID ens = new TSEntitiesNodeID(this.ClassID);
                ens.RetrieveAllFromDBSource();
                return ens.ToJson();
            }

            throw new Exception("err@没有判断的entity类型. Entities_RetrieveAllFromDBSource ");
        }

        public string Entities_RetrieveAll()
        {
            if (this.PK.Equals("No") == true)
            {
                TSEntitiesNoName ens = new TSEntitiesNoName(this.ClassID);
                ens.RetrieveAll(this.OrderBy);
                return ens.ToJson();
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntitiesOID ens = new TSEntitiesOID(this.ClassID);
                ens.RetrieveAll(this.OrderBy);
                return ens.ToJson();
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntitiesMyPK ens = new TSEntitiesMyPK(this.ClassID);
                ens.RetrieveAll(this.OrderBy);
                return ens.ToJson();
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntitiesWorkID ens = new TSEntitiesWorkID(this.ClassID);
                ens.RetrieveAll(this.OrderBy);
                return ens.ToJson();
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntitiesNodeID ens = new TSEntitiesNodeID(this.ClassID);
                ens.RetrieveAll(this.OrderBy);
                return ens.ToJson();
            }

            throw new Exception("err@没有判断的entity类型. Entities_RetrieveAll ");
        }

        public string Entities_Retrieve()
        {
            if (this.PK.Equals("No") == true)
            {
                TSEntitiesNoName ens = new TSEntitiesNoName(this.ClassID);
                BP.WF.HttpHandler.WF_Comm hand = new WF_Comm();
                return hand.Entities_Init_Ext(ens, ens.GetNewEntity, this.Paras);
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntitiesMyPK ens = new TSEntitiesMyPK(this.ClassID);
                BP.WF.HttpHandler.WF_Comm hand = new WF_Comm();
                return hand.Entities_Init_Ext(ens, ens.GetNewEntity, this.Paras);
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntitiesNodeID ens = new TSEntitiesNodeID(this.ClassID);
                BP.WF.HttpHandler.WF_Comm hand = new WF_Comm();
                return hand.Entities_Init_Ext(ens, ens.GetNewEntity, this.Paras);
            }


            if (this.PK.Equals("WorkID") == true)
            {
                TSEntitiesWorkID ens = new TSEntitiesWorkID(this.ClassID);
                BP.WF.HttpHandler.WF_Comm hand = new WF_Comm();
                return hand.Entities_Init_Ext(ens, ens.GetNewEntity, this.Paras);
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntitiesOID ens = new TSEntitiesOID(this.ClassID);
                BP.WF.HttpHandler.WF_Comm hand = new WF_Comm();
                return hand.Entities_Init_Ext(ens, ens.GetNewEntity, this.Paras);
            }


            throw new Exception("err@没有判断的 entity 类型. Entities_Retrieve ");
        }

        public string Entities_RetrieveIn()
        {
            string retrieveKey = this.GetRequestVal("Key");
            string retrieveVal = this.GetRequestVal("Vals");
            if (this.PK.Equals("No") == true)
            {
                TSEntitiesNoName ens = new TSEntitiesNoName(this.ClassID);
                ens.RetrieveIn(retrieveKey, retrieveVal);
                return ens.ToJson("dt");
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntitiesMyPK ens = new TSEntitiesMyPK(this.ClassID);
                ens.RetrieveIn(retrieveKey, retrieveVal);
                return ens.ToJson("dt");
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntitiesNodeID ens = new TSEntitiesNodeID(this.ClassID);
                ens.RetrieveIn(retrieveKey, retrieveVal);
                return ens.ToJson("dt");
            }


            if (this.PK.Equals("WorkID") == true)
            {
                TSEntitiesWorkID ens = new TSEntitiesWorkID(this.ClassID);
                ens.RetrieveIn(retrieveKey, retrieveVal);
                return ens.ToJson("dt");
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntitiesOID ens = new TSEntitiesOID(this.ClassID);
                ens.RetrieveIn(retrieveKey, retrieveVal);
                return ens.ToJson("dt");
            }

            throw new Exception("err@没有判断的 entity 类型. Entities_Retrieve ");
        }

        /**
 * 批量更新
 * @return
 * @throws Exception
 */
        public string Entities_Update()
        {
            Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
            if (json == null)
            {
                return "err@请传入要更新的数据Ï";
            }

            string idListStr = this.GetRequestVal("IdListStr");
            Entities ens = ClassFactory.GetEns(ClassID);
            if (ens == null)
            {
                return "err@获取实体失败，请检查参数，className = " + EnsName;
            }

            Entity en = ens.GetNewEntity;
            if (en == null)
            {
                return "err@获取实体失败，请检查参数，className = " + EnsName;
            }

            string PKField = ens.GetNewEntity.PK;
            string pTable = en.EnMap.PhysicsTable;
            StringBuilder sql = new StringBuilder("update " + pTable + " set ");

            foreach (var item in json)
            {
                string key = item.Key;
                string val = item.Value.ToString();
                if (item.Value.Type == JTokenType.String)
                    sql.Append(key).Append("='").Append(val).Append("',");
                else if (item.Value.Type == JTokenType.Integer || item.Value.Type == JTokenType.Float)
                    sql.Append(key).Append("=").Append(val).Append(",");
                else if (item.Value.Type == JTokenType.Boolean)
                {
                    string _v = item.Value.ToString();
                    if (_v.ToLower().Equals("true") || _v.ToLower().Equals("1"))
                        _v = "1";
                    else
                        _v = "0";
                    sql.Append(key).Append("=").Append(_v).Append(",");
                }
                else
                {
                    sql.Append(key).Append("=").Append(val).Append(",");
                }
            }
            sql.Remove(sql.Length - 1, 1);
            return UpdateByRange(idListStr, PKField, sql);
        }

        /**
         * 从某一列更新
         * @return
         * @throws Exception
         */
        public string Entities_UpdateFromColumn()
        {
            Entities ens = ClassFactory.GetEns(ClassID);
            if (ens == null)
            {
                return "err@获取实体失败，请检查参数，className = " + ClassID;
            }

            Entity en = ens.GetNewEntity;
            if (en == null)
            {
                return "err@获取实体失败，请检查参数，className = " + ClassID;
            }

            string fromColumn = this.GetRequestVal("FromColumn");
            string toColumn = this.GetRequestVal("ToColumn");
            string idListStr = this.GetRequestVal("IdListStr");
            string PKField = en.PK;
            string pTable = en.EnMap.PhysicsTable;
            StringBuilder sql = new StringBuilder("update " + pTable + " set ");
            sql.Append(fromColumn).Append("=").Append(toColumn);
            return UpdateByRange(idListStr, PKField, sql);
        }


        private string UpdateByRange(string idListStr, string PKField, StringBuilder sql)
        {
            if (!string.IsNullOrEmpty(idListStr))
            {
                var ids = idListStr.Split(',')
                    .Select(id => id.Trim())
                    .Select(id => $"'{id}'")
                    .ToArray();

                if (ids.Length > 0)
                {
                    sql.Append(" WHERE ").Append(PKField).Append(" IN (").Append(string.Join(",", ids)).Append(")");
                }
            }

            DBAccess.RunSQL(sql.ToString());
            return "更新成功";
        }


        /**
         * 通过id删除集合数据
         * @return
         * @throws Exception
         */
        public string Entities_DeleteByIdList()
        {
            Entities ens = ClassFactory.GetEns(ClassID);
            if (ens == null)
            {
                return "err@获取实体失败，请检查参数，className = " + ClassID;
            }

            Entity en = ens.GetNewEntity;
            if (en == null)
            {
                return "err@获取实体失败，请检查参数，className = " + ClassID;
            }

            string PKField = en.PK;
            string pTable = en.EnMap.PhysicsTable;
            string idListArgs = this.GetRequestVal("idList");
            if (idListArgs.IsBlank())
            {
                return "err@请传入要删除的id";
            }

            string reverse = this.GetRequestVal("reverse");
            string r = "";
            if (!reverse.IsBlank() && reverse.Equals("1"))
            {
                r = "not";
            }

            var ids = idListArgs.Split(',')
                .Select(id => $"'{id.Trim()}'")
                .ToArray();
            string sql = $"DELETE FROM {pTable} WHERE {PKField} {r} IN ({string.Join(",", ids)})";
            DBAccess.RunSQL(sql);
            return "删除成功";
        }

        public string Entities_RetrieveOR()
        {
            string retrieveKey = this.GetRequestVal("Key");
            string retrieveVal = this.GetRequestVal("Val");
            string key1 = this.GetRequestVal("Key1");
            string val1 = this.GetRequestVal("Val1");
            string orderBy = this.GetRequestVal("OrderBy");
            if (this.PK.Equals("No") == true)
            {
                TSEntitiesNoName ens = new TSEntitiesNoName(this.ClassID);
                QueryObject qo = new QueryObject(ens);
                qo.AddWhere(retrieveKey, retrieveVal);
                qo.addOr();
                qo.AddWhere(key1, val1);
                qo.addOrderBy(orderBy);
                qo.DoQuery();
                return ens.ToJson("dt");
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntitiesMyPK ens = new TSEntitiesMyPK(this.ClassID);
                QueryObject qo = new QueryObject(ens);
                qo.AddWhere(retrieveKey, retrieveVal);
                qo.addOr();
                qo.AddWhere(key1, val1);
                qo.addOrderBy(orderBy);
                qo.DoQuery();
                return ens.ToJson("dt");
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntitiesNodeID ens = new TSEntitiesNodeID(this.ClassID);
                QueryObject qo = new QueryObject(ens);
                qo.AddWhere(retrieveKey, retrieveVal);
                qo.addOr();
                qo.AddWhere(key1, val1);
                qo.addOrderBy(orderBy);
                qo.DoQuery();
                return ens.ToJson("dt");
            }


            if (this.PK.Equals("WorkID") == true)
            {
                TSEntitiesWorkID ens = new TSEntitiesWorkID(this.ClassID);
                QueryObject qo = new QueryObject(ens);
                qo.AddWhere(retrieveKey, retrieveVal);
                qo.addOr();
                qo.AddWhere(key1, val1);
                qo.addOrderBy(orderBy);
                qo.DoQuery();
                return ens.ToJson("dt");
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntitiesOID ens = new TSEntitiesOID(this.ClassID);
                QueryObject qo = new QueryObject(ens);
                qo.AddWhere(retrieveKey, retrieveVal);
                qo.addOr();
                qo.AddWhere(key1, val1);
                qo.addOrderBy(orderBy);
                qo.DoQuery();
                return ens.ToJson("dt");
            }

            throw new Exception("err@没有判断的 entity 类型. Entities_Retrieve ");
        }

        public string Entities_Delete()
        {
            //检查是否是系统表.
            this.CheckAdminPower("TSEntitiesNoName", "Entity_Delete");

            //判断admin权限,如果不能处理系统就会抛出异常.
            //  GEEntitys ens = new GEEntitys(this.ClassID);
            Entities ens = ClassFactory.GetEns(this.ClassID);

            BP.WF.HttpHandler.WF_Comm hand = new WF_Comm();
            Entities myens = hand.Entities_Delete_Ext_GetEns(ens); //获得删除的实体.
            if (myens.Count == 0)
                return "info@要删除的数据为空.";
            string info = "";
            string ptable = myens[0].GetNewEntities.GetNewEntity.EnMap.PhysicsTable;
            foreach (Entity item in myens)
            {
                try
                {
                    this.CheckDeletePower(ptable, item); //检查删除的权限.
                    item.Delete(); //执行删除.
                }
                catch (Exception ex)
                {
                    info += " err@删除错误:[" + item.ClassID + "]" + item.PKVal + "," + ex.Message;
                }
            }

            return info;
        }

        public string Entities_RetrieveLikeKey()
        {
            string searchKey = this.GetRequestVal("SearchKey");
            string attrsScop = this.GetRequestVal("AttrsScop");
            string condAttr = this.GetRequestVal("CondAttr");
            string condVal = this.GetRequestVal("CondVal");
            string orderBy = this.GetRequestVal("OrderBy");

            if (this.PK.Equals("No") == true)
            {
                TSEntitiesNoName ens = new TSEntitiesNoName(this.ClassID);
                QueryObject qo = new QueryObject(ens);

                string[] strs = attrsScop.Split(',');

                qo.addLeftBracket();
                foreach (string str in strs)
                {
                    if (DataType.IsNullOrEmpty(str) == true)
                        continue;
                    qo.AddWhere(str, " LIKE ", "'%" + searchKey + "%'");
                    qo.addOr();
                }

                qo.AddWhere(" 1=2 ");
                qo.addRightBracket();

                if (DataType.IsNullOrEmpty(condAttr) == false)
                {
                    qo.addAnd();
                    qo.AddWhere(condAttr, "=", condVal);
                }

                if (DataType.IsNullOrEmpty(orderBy) == false)
                    qo.addOrderBy(orderBy);
                qo.DoQuery();
                return ens.ToJson();
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntitiesMyPK ens = new TSEntitiesMyPK(this.ClassID);
                QueryObject qo = new QueryObject(ens);
                string[] strs = attrsScop.Split(',');

                qo.addLeftBracket();
                foreach (string str in strs)
                {
                    if (DataType.IsNullOrEmpty(str) == true || str.Equals("MyPK"))
                        continue;
                    qo.AddWhere(str, " LIKE ", "'%" + searchKey + "%'");
                    qo.addOr();
                }

                qo.AddWhere(" 1=2 ");
                qo.addRightBracket();

                if (DataType.IsNullOrEmpty(condAttr) == false)
                {
                    qo.addAnd();
                    qo.AddWhere(condAttr, "=", condVal);
                }

                if (DataType.IsNullOrEmpty(orderBy) == false)
                    qo.addOrderBy(orderBy);
                qo.DoQuery();
                return ens.ToJson();
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntitiesOID ens = new TSEntitiesOID(this.ClassID);
                QueryObject qo = new QueryObject(ens);

                string[] strs = attrsScop.Split(',');

                qo.addLeftBracket();
                foreach (string str in strs)
                {
                    if (DataType.IsNullOrEmpty(str) == true)
                        continue;
                    qo.AddWhere(str, " LIKE ", "'%" + searchKey + "%'");
                    qo.addOr();
                }

                qo.AddWhere(" 1=2 ");
                qo.addRightBracket();

                if (DataType.IsNullOrEmpty(condAttr) == false)
                {
                    qo.addAnd();
                    qo.AddWhere(condAttr, "=", condVal);
                }

                if (DataType.IsNullOrEmpty(orderBy) == false)
                    qo.addOrderBy(orderBy);
                qo.DoQuery();
                return ens.ToJson();
            }

            return "err@没有判断的类型Entities_RetrieveLikeKey:" + this.PK;
        }

        #endregion 实体集合操作.

        #region 实体操作.

        /// <summary>
        /// 加入map到缓存.
        /// </summary>
        /// <returns></returns>
        public string Entity_SetMap()
        {
            string key = SystemConfig.GetIsEncryptionKey();
            string mapInfo = this.Map;
            string uriComponent = BP.Tools.AESHelper.AESDecrypt(mapInfo, key);
            string mapStr = Uri.UnescapeDataString(uriComponent);
            BP.EnTS.Glo.SetMap(this.ClassID, mapStr);
            return "1";
        }

        /// <summary>
        /// 检查是否存在Map
        /// </summary>
        /// <returns></returns>
        public string Entity_IsExitMap()
        {
            //缓存map.
            if (BP.EnTS.Glo.IsExitMap(this.ClassID) == true)
                return "1";

            return "0";
        }

        public string Entity_IsExits()
        {
            if (this.PK.Equals("No") == true)
            {
                TSEntityNoName en = new TSEntityNoName(this.ClassID);
                en.No = this.PKVal;
                if (en.IsExits == true)
                    return "1";
                return "0";
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntityMyPK en = new TSEntityMyPK(this.ClassID);
                en.MyPK = this.PKVal;
                if (en.IsExits == true)
                    return "1";
                return "0";
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntityOID en = new TSEntityOID(this.ClassID);
                en.OID = int.Parse(this.PKVal);
                if (en.IsExits == true)
                    return "1";
                return "0";
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntityWorkID en = new TSEntityWorkID(this.ClassID);
                en.WorkID = int.Parse(this.PKVal);
                if (en.IsExits == true)
                    return "1";
                return "0";
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntityNodeID en = new TSEntityNodeID(this.ClassID);
                en.NodeID = int.Parse(this.PKVal);
                if (en.IsExits == true)
                    return "1";
                return "0";
            }

            throw new Exception("err@没有判断的entity类型.");
        }

        /// <summary>
        /// 执行insert方法.
        /// </summary>
        /// <returns></returns>
        public string Entity_Insert()
        {
            if (this.PK.Equals("No") == true)
            {
                TSEntityNoName en = new TSEntityNoName(this.ClassID);

                // 判断admin权限.
                this.CheckAdminPower(this.PKVal, "Entity_Insert");
                this.CheckInsertPower(en.EnMap.PhysicsTable); //检查设定的权限.

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                en.Insert();
                return en.ToJson();
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntityMyPK en = new TSEntityMyPK(this.ClassID);
                // 判断admin权限.
                this.CheckAdminPower(this.PKVal, "Entity_Insert");
                this.CheckInsertPower(en.EnMap.PhysicsTable); //检查设定的权限.

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                if (en.GetValIntByKey("Idx", -1) == -1)
                {
                    en.SetValByKey("Idx", int.Parse(DateTime.Now.ToString("MMddHHmmss")));
                }

                en.Insert();
                return en.ToJson();
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntityOID en = new TSEntityOID(this.ClassID);
                // 判断admin权限.
                this.CheckAdminPower(this.PKVal, "Entity_Insert");
                this.CheckInsertPower(en.EnMap.PhysicsTable); //检查设定的权限.

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                if (en.OID != 0)
                    en.InsertAsOID(en.OID);
                else
                    en.Insert();
                return en.ToJson();
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntityWorkID en = new TSEntityWorkID(this.ClassID);
                // 判断admin权限.
                this.CheckAdminPower(this.PKVal, "Entity_Insert");
                this.CheckInsertPower(en.EnMap.PhysicsTable); //检查设定的权限.

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                en.Insert();
                return en.ToJson();
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntityNodeID en = new TSEntityNodeID(this.ClassID);
                // 判断admin权限.
                this.CheckAdminPower(this.PKVal, "Entity_Insert");
                this.CheckInsertPower(en.EnMap.PhysicsTable); //检查设定的权限.

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                en.Insert();
                return en.ToJson();
            }

            throw new Exception("err@没有判断的entity类型.");
        }

        /// <summary>
        /// 根据
        /// </summary>
        /// <returns></returns>
        public string Entity_GenerSQLAttrDB()
        {
            DataTable dt = null;
            string attrKey = this.GetRequestVal("AttrKey"); //  "SELECT * FROM WHERE XX=@SortNo ";
            if (this.PK.Equals("NodeID") == true)
            {
                TSEntityNodeID en = new TSEntityNodeID(this.ClassID);
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    en.SetValByKey(item.Key, item.Value);
                }

                Attr attr = en.EnMap.GetAttrByKey(attrKey);
                string sql = attr.UIBindKey;
                sql = BP.WF.Glo.DealExp(sql, en);
                dt = DBAccess.RunSQLReturnTable(sql);
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntityMyPK en = new TSEntityMyPK(this.ClassID);
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    en.SetValByKey(item.Key, item.Value);
                }

                Attr attr = en.EnMap.GetAttrByKey(attrKey);
                string sql = attr.UIBindKey;
                sql = BP.WF.Glo.DealExp(sql, en);
                dt = DBAccess.RunSQLReturnTable(sql);
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntityWorkID en = new TSEntityWorkID(this.ClassID);
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    en.SetValByKey(item.Key, item.Value);
                }

                Attr attr = en.EnMap.GetAttrByKey(attrKey);
                string sql = attr.UIBindKey;
                sql = BP.WF.Glo.DealExp(sql, en);
                dt = DBAccess.RunSQLReturnTable(sql);
            }

            if (this.PK.Equals("No") == true)
            {
                TSEntityNoName en = new TSEntityNoName(this.ClassID);
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    en.SetValByKey(item.Key, item.Value);
                }

                Attr attr = en.EnMap.GetAttrByKey(attrKey);
                string sql = attr.UIBindKey;
                sql = BP.WF.Glo.DealExp(sql, en);
                dt = DBAccess.RunSQLReturnTable(sql);
            }

            if (dt == null)
                return "";
            if (SystemConfig.AppCenterDBFieldCaseModel != FieldCaseModel.None)
            {
                string columnName = "";
                foreach (DataColumn col in dt.Columns)
                {
                    columnName = col.ColumnName.ToUpper();
                    switch (columnName)
                    {
                        case "NO":
                            col.ColumnName = "No";
                            break;
                        case "NAME":
                            col.ColumnName = "Name";
                            break;
                    }
                }
            }

            return BP.Tools.Json.ToJson(dt);
        }

        public string Entity_Save()
        {
            //判断admin权限.
            this.CheckAdminPower(this.PKVal, "Entity_Save");

            if (this.PK.Equals("No") == true)
            {
                TSEntityNoName en = new TSEntityNoName(this.ClassID);
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                /*如果包含编号。 */
                if (en.IsExits)
                {
                    CheckUpdatePower(en.EnMap.PhysicsTable, en); //检查是否有更新的权限.
                    return en.Update().ToString();
                }
                else
                {
                    CheckInsertPower(en.EnMap.PhysicsTable); //检查是否有新建.
                    if (en.EnMap.ItIsAutoGenerNo
                        && en.EnMap.GetAttrByKey("No").UIIsReadonly)
                        en.No = en.GenerNewNo;
                    en.Insert();
                    return "0";
                }
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntityOID en = new TSEntityOID(this.ClassID);
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                if (en.OID == 0)
                    CheckInsertPower(en.EnMap.PhysicsTable); //检查是否有更新的权限.
                else
                    CheckUpdatePower(en.EnMap.PhysicsTable, en); //检查是否有更新的权限.

                int num = en.Save();
                return num.ToString();
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntityMyPK en = new TSEntityMyPK(this.ClassID);
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                if (DataType.IsNullOrEmpty(en.MyPK) == true)
                    CheckInsertPower(en.EnMap.PhysicsTable); //检查是否有更新的权限.
                else
                    CheckUpdatePower(en.EnMap.PhysicsTable, en); //检查是否有更新的权限.

                int num = en.Save();
                return num.ToString();
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntityWorkID en = new TSEntityWorkID(this.ClassID);
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                if (en.WorkID == 0)
                    CheckInsertPower(en.EnMap.PhysicsTable); //检查是否有更新的权限.
                else
                    CheckUpdatePower(en.EnMap.PhysicsTable, en); //检查是否有更新的权限.

                int num = en.Save();
                return num.ToString();
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntityNodeID en = new TSEntityNodeID(this.ClassID);
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                if (en.NodeID == 0)
                    CheckInsertPower(en.EnMap.PhysicsTable); //检查是否有更新的权限.
                else
                    CheckUpdatePower(en.EnMap.PhysicsTable, en); //检查是否有更新的权限.

                int num = en.Save();
                return num.ToString();
            }

            throw new Exception("err@没有判断的entity类型.");
        }

        /// <summary>
        /// 执行更新
        /// </summary>
        /// <returns></returns>
        public string Entity_Update()
        {
            //判断admin权限.
            this.CheckAdminPower(this.PKVal, "Entity_Save");

            // checkPower(this.ClassID, this.PKVal);
            if (this.PK.Equals("No") == true)
            {
                TSEntityNoName en = new TSEntityNoName(this.ClassID, this.PKVal);
                CheckUpdatePower(en.EnMap.PhysicsTable, en); //检查权限.

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                en.No = this.PKVal;

                string val = en.Update().ToString();

                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    string paraFields = en.EnMap.ParaFields;
                    if (DataType.IsNullOrEmpty(paraFields)) paraFields = "";
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKVal;
                    enServ.RetrieveFromDBSources();
                    foreach (var item in json)
                    {
                        if (item.Value == null || item.Value.Equals("null"))
                            enServ.SetValByKey(item.Key, "");
                        else
                            enServ.SetValByKey(item.Key, item.Value);

                        if (paraFields.Contains("," + item.Key.ToString() + ","))
                            enServ.SetPara(item.Key.ToString(), item.Value.ToString());
                    }

                    enServ.Update();
                }

                return val;
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntityMyPK en = new TSEntityMyPK(this.ClassID, this.PKVal);
                CheckUpdatePower(en.EnMap.PhysicsTable, en); //检查权限.

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                en.MyPK = this.PKVal;

                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKVal;
                    enServ.RetrieveFromDBSources();
                    foreach (var item in json)
                    {
                        if (item.Value == null || item.Value.Equals("null"))
                            enServ.SetValByKey(item.Key, "");
                        else
                            enServ.SetValByKey(item.Key, item.Value);
                    }

                    enServ.Update();

                    //把变更后的值给,TS实体.
                    Row row = enServ.Row;
                    foreach (var key in row.Keys)
                        en.Row[key] = row[key];
                }

                return en.Update().ToString();
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntityOID en = new TSEntityOID(this.ClassID, this.PKValInt);
                CheckUpdatePower(en.EnMap.PhysicsTable, en); //检查权限.

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKValInt;
                    enServ.RetrieveFromDBSources();
                    foreach (var item in json)
                    {
                        if (item.Value == null || item.Value.Equals("null"))
                            enServ.SetValByKey(item.Key, "");
                        else
                            enServ.SetValByKey(item.Key, item.Value);
                    }

                    enServ.Update();
                }

                en.OID = this.PKValInt;
                return en.Update().ToString();
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntityNodeID en = new TSEntityNodeID(this.ClassID, this.PKValInt);
                CheckUpdatePower(en.EnMap.PhysicsTable, en); //检查权限.

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }

                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKVal;
                    enServ.RetrieveFromDBSources();
                    foreach (var item in json)
                    {
                        if (item.Value == null || item.Value.Equals("null"))
                            enServ.SetValByKey(item.Key, "");
                        else
                            enServ.SetValByKey(item.Key, item.Value);
                    }

                    enServ.Update();
                }

                en.NodeID = this.PKValInt;
                return en.Update().ToString();
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntityWorkID en = new TSEntityWorkID(this.ClassID, this.PKValInt);
                //检查权限.
                CheckUpdatePower(en.EnMap.PhysicsTable, en);

                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(this.GetRequestVal("Row"));
                foreach (var item in json)
                {
                    if (item.Value == null || item.Value.Equals("null"))
                        en.SetValByKey(item.Key, "");
                    else
                        en.SetValByKey(item.Key, item.Value);
                }


                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKValInt;
                    enServ.RetrieveFromDBSources();
                    foreach (var item in json)
                    {
                        if (item.Value == null || item.Value.Equals("null"))
                            enServ.SetValByKey(item.Key, "");
                        else
                            enServ.SetValByKey(item.Key, item.Value);
                    }

                    enServ.Update();
                }

                en.WorkID = this.PKValInt;
                return en.Update().ToString();
            }

            throw new Exception("err@没有判断的entity类型. Entity_Update ");
        }

        /// <summary>
        /// 查询 
        /// </summary>
        /// <returns></returns>
        public string Entity_Retrieve()
        {
            if (this.PK.Equals("No") == true)
            {
                TSEntityNoName en = null;
                try
                {
                    en = new TSEntityNoName(this.ClassID, this.PKVal);
                    return en.ToJson();
                }
                catch (Exception ex)
                {
                    en = new TSEntityNoName(this.ClassID);
                    en.CheckPhysicsTable();
                    en = new TSEntityNoName(this.ClassID, this.PKVal);
                    return en.ToJson();
                }
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntityMyPK en = new TSEntityMyPK(this.ClassID, this.PKVal);
                return en.ToJson();
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntityOID en = new TSEntityOID(this.ClassID, PKValInt);
                return en.ToJson();
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntityWorkID en = new TSEntityWorkID(this.ClassID, this.PKValInt);
                return en.ToJson();
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntityNodeID en = new TSEntityNodeID(this.ClassID, this.PKValInt);
                return en.ToJson();
            }

            throw new Exception("err@没有判断的entity类型. Entity_Retrieve ");
        }

        /// <summary>
        /// 从数据库里查询.
        /// </summary>
        /// <returns></returns>
        public string Entity_RetrieveFromDBSources()
        {
            if (this.PK.Equals("No") == true)
            {
                TSEntityNoName en = new TSEntityNoName(this.ClassID);
                en.No = this.PKVal;
                int val = en.RetrieveFromDBSources();
                if (val == 0) return "0";
                return en.ToJson();
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntityMyPK en = new TSEntityMyPK(this.ClassID);
                en.MyPK = this.PKVal;
                int val = en.RetrieveFromDBSources();
                if (val == 0) return "0";
                return en.ToJson();
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntityOID en = new TSEntityOID(this.ClassID);
                en.OID = this.PKValInt;
                int val = en.RetrieveFromDBSources();
                if (val == 0)
                    return "0";
                return en.ToJson();
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntityWorkID en = new TSEntityWorkID(this.ClassID);
                en.WorkID = this.PKValInt;
                int val = en.RetrieveFromDBSources();
                if (val == 0) return "0";
                return en.ToJson();
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntityNodeID en = new TSEntityNodeID(this.ClassID);
                en.NodeID = this.PKValInt;
                int val = en.RetrieveFromDBSources();
                if (val == 0) return "0";
                return en.ToJson();
            }

            throw new Exception("err@没有判断的entity类型. Entity_Retrieve ");
        }

        /// <summary>
        /// 执行删除
        /// </summary>
        /// <returns></returns>
        public string Entity_Delete()
        {
            BP.Sys.Base.Glo.WriteEntityLog("实体数据删除", this.ClassID, this.PK, this.PKVal, this.GetRequestVal("Row"));
            //判断admin权限,如果不能处理系统就会抛出异常.
            this.CheckAdminPower(this.PKVal, "Entity_Delete");
            if (this.PK.Equals("No") == true)
            {
                TSEntityNoName en = new TSEntityNoName(this.ClassID);
                en.No = this.PKVal;
                en.RetrieveFromDBSources();
                //检查权限.
                CheckDeletePower(en.EnMap.PhysicsTable, en);

                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKVal;
                    enServ.RetrieveFromDBSources();
                    int i = enServ.Delete();

                    en.Delete(); //执行本实体的删除.
                    return i.ToString();
                }

                return en.Delete().ToString();
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntityMyPK en = new TSEntityMyPK(this.ClassID);
                en.MyPK = this.PKVal;
                if (en.RetrieveFromDBSources() == 1)
                    CheckDeletePower(en.EnMap.PhysicsTable, en); //检查权限.

                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKVal;
                    enServ.RetrieveFromDBSources();
                    int i = enServ.Delete();

                    en.Delete(); //执行本实体的删除.
                    return i.ToString();
                }

                return en.Delete().ToString();
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntityOID en = new TSEntityOID(this.ClassID);
                en.OID = this.PKValInt;
                if (en.RetrieveFromDBSources() == 1)
                    CheckDeletePower(en.EnMap.PhysicsTable, en); //检查权限.

                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKVal;
                    enServ.RetrieveFromDBSources();
                    int i = enServ.Delete();

                    en.Delete(); //执行本实体的删除. 
                    return i.ToString();
                }

                return en.Delete().ToString();
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntityWorkID en = new TSEntityWorkID(this.ClassID);
                en.WorkID = this.PKValInt;
                if (en.RetrieveFromDBSources() == 1)
                    CheckDeletePower(en.EnMap.PhysicsTable, en); //检查权限.

                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKVal;
                    enServ.RetrieveFromDBSources();
                    int i = enServ.Delete();

                    en.Delete(); //执行本实体的删除.
                    return i.ToString();
                }

                return en.Delete().ToString();
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntityNodeID en = new TSEntityNodeID(this.ClassID);
                en.NodeID = this.PKValInt;
                if (en.RetrieveFromDBSources() == 1)
                    CheckDeletePower(en.EnMap.PhysicsTable, en); //检查权限.

                //判断是否有对应的后端实体类，如果有则要执行更新.
                if (DataType.IsNullOrEmpty(this.RefEnName) == false)
                {
                    Entity enServ = ClassFactory.GetEn(this.RefEnName);
                    if (enServ == null)
                        throw new Exception("err@TS实体类[" + this.ClassID + "]关联的[" + this.RefEnName + "]拼写错误,");

                    enServ.PKVal = this.PKVal;
                    enServ.RetrieveFromDBSources();
                    int i = enServ.Delete();

                    en.Delete(); //执行本实体的删除.
                    return i.ToString();
                }

                return en.Delete().ToString();
            }

            throw new Exception("err@没有判断的entity类型. Entity_Delete ");
        }

        public string Entity_Upload()
        {
            if (HttpContextHelper.RequestFilesCount == 0)
                return "err@请选择要上传的文件。";
            //获取保存文件信息的实体
            string saveTo = this.GetRequestVal("SaveTo");
            string realSaveTo = "";
            if (DataType.IsNullOrEmpty(saveTo) == true)
            {
                realSaveTo = SystemConfig.PathOfDataUser + "UploadFile/";
                saveTo = "/DataUser/UploadFile/";
            }
            else
            {
                if (saveTo.StartsWith("/DataUser"))
                {
                    realSaveTo = SystemConfig.PathOfWebApp + saveTo;

                    //DataUser路径去重
                    realSaveTo = realSaveTo.Replace("DataUser//DataUser", "DataUser");
                }
            }

            //获取文件的名称
            string fileName = HttpContextHelper.GetNameByIdx(0);
            if (fileName.IndexOf("/") >= 0)
                fileName = fileName.Substring(fileName.LastIndexOf("/") + 1);
            fileName = fileName.Substring(0, fileName.LastIndexOf('.'));
            //文件后缀
            string ext = System.IO.Path.GetExtension(HttpContextHelper.GetNameByIdx(0));

            //文件大小
            float size = HttpContextHelper.RequestFileLength(HttpContextHelper.RequestFiles(0)) / 1024;

            FileInfo info = new FileInfo(saveTo);
            HttpContextHelper.UploadFile(HttpContextHelper.RequestFiles(0), realSaveTo + fileName + ext);

            #region 上传RTF模板时，清空缓存

            if (saveTo.IndexOf("/DataUser/CyclostyleFile/") != -1)
            {
                BP.DA.Cache.Bill_Cache.Clear();
            }

            #endregion 上传RTF模板时，清空缓存

            AtPara para = new AtPara();
            para.SetVal("FileName", fileName);
            para.SetVal("FileExt", ext);
            para.SetVal("FileSize", size.ToString());
            para.SetVal("FilePath", saveTo + fileName + ext);
            string saveInfo = para.GenerAtParaStrs();
            if (this.PK.Equals("No") == true)
            {
                TSEntityNoName en = new TSEntityNoName(this.ClassID, this.PKVal);
                en.No = this.PKVal;
                en.SetValByKey(this.KeyOfEn, saveInfo);
                return en.DirectUpdate().ToString();
            }

            if (this.PK.Equals("MyPK") == true)
            {
                TSEntityMyPK en = new TSEntityMyPK(this.ClassID, this.PKVal);
                en.MyPK = this.PKVal;
                en.SetValByKey(this.KeyOfEn, saveInfo);
                return en.DirectUpdate().ToString();
            }

            if (this.PK.Equals("OID") == true)
            {
                TSEntityOID en = new TSEntityOID(this.ClassID, this.PKValInt);
                en.OID = this.PKValInt;
                en.SetValByKey(this.KeyOfEn, saveInfo);
                return en.DirectUpdate().ToString();
            }

            if (this.PK.Equals("NodeID") == true)
            {
                TSEntityNodeID en = new TSEntityNodeID(this.ClassID, this.PKValInt);
                en.NodeID = this.PKValInt;
                en.SetValByKey(this.KeyOfEn, saveInfo);
                return en.DirectUpdate().ToString();
            }

            if (this.PK.Equals("WorkID") == true)
            {
                TSEntityWorkID en = new TSEntityWorkID(this.ClassID, this.PKValInt);
                en.WorkID = this.PKValInt;
                en.SetValByKey(this.KeyOfEn, saveInfo);
                return en.DirectUpdate().ToString();
            }

            return "上传成功";
        }

        public string Entity_DBRoleAttrs()
        {
            if (DataType.IsNullOrEmpty(this.EnName) == true)
                return "";
            DBRoles dbRoles = new DBRoles();
            dbRoles.Retrieve(DBRoleAttr.FrmID, this.EnName, DBRoleAttr.DBRole, "ShowAttrs", DBRoleAttr.IsEnable, 1);
            return CheckDB(dbRoles);
        }
        public string Entity_DBRoleMethods()
        {
            if (DataType.IsNullOrEmpty(this.EnName) == true)
                return "";
            DBRoles dbRoles = new DBRoles();
            dbRoles.Retrieve(DBRoleAttr.FrmID, this.EnName, DBRoleAttr.DBRole, "ShowMethod", DBRoleAttr.IsEnable, 1);
            return CheckDB(dbRoles);
        }
        private string CheckDB(DBRoles dbRoles)
        {
            if (dbRoles.Count == 0)
                return "";
            Entity en = dbRoles.GetEntityByKey(DBRoleAttr.MarkID, "None");
            if (en != null)
                return "";
            //获取是否存在管理员，二级管理员
            en = dbRoles.GetEntityByKey(DBRoleAttr.MarkID, "Adminer");
            if (en != null && WebUser.No.Equals("admin"))
                return "";
            string keyOfEns = ",";
            foreach (DBRole dbRole in dbRoles)
            {
                string strs = "," + dbRole.Docs + ",";
                string sql = "";
                //二级管理员
                if (dbRole.MarkID.Equals("Admin2") == true)
                {
                    if (WebUser.IsAdmin == true)
                    {
                        keyOfEns += dbRole.GetValStringByKey("Objs") + ",";
                        break;
                    }
                }
                //如果是部门.
                if (dbRole.MarkID.Equals("ByDepts") == true)
                {
                    sql = "SELECT FK_Dept FROM Port_DeptEmp WHERE FK_Emp='" + WebUser.No + "'";
                    sql += " UNION ";
                    sql += "SELECT FK_Dept FROM Port_DeptEmpStation WHERE FK_Emp='" + WebUser.No + "'";

                    DataTable mydt = DBAccess.RunSQLReturnTable(sql);
                    foreach (DataRow mydr in mydt.Rows)
                    {
                        string myNo = mydr[0].ToString();
                        if (strs.Contains("," + myNo + ",") == true)
                        {
                            keyOfEns += dbRole.GetValStringByKey("Objs") + ",";
                            break;
                        }
                    }
                }

                //如果标记是岗位.
                if (dbRole.MarkID.Equals("ByStations") == true)
                {
                    sql = "SELECT FK_Station FROM Port_DeptEmpStation WHERE FK_Emp='" + WebUser.No + "'";
                    DataTable mydt = DBAccess.RunSQLReturnTable(sql);
                    foreach (DataRow mydr in mydt.Rows)
                    {
                        string myNo = mydr[0].ToString();
                        if (strs.Contains("," + myNo + ",") == true)
                        {
                            keyOfEns += dbRole.GetValStringByKey("Objs") + ",";
                            break;
                        }
                    }
                }

                //指定的人是否可以查看全部数据?.
                if (dbRole.MarkID.Equals("ByEmps") == true)
                {
                    if (strs.Contains("," + WebUser.No + ",") == true)
                    {
                        keyOfEns += dbRole.GetValStringByKey("Objs") + ",";
                        break;
                    }
                }
            }
            return keyOfEns;
        }
        #endregion 实体操作.
    }
}